package wpmp.security.client.internal;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wcommons.httputils.HttpUtils;
import wcommons.httputils.quickbean.RespInfo;
import wpmp.security.client.SecurityConfig;
import wpmp.utils.quickbean.Code;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:50:15 AM Dec 4, 2013
 */
public class PmpCodeUtils {

	private static final Log log = LogFactory.getLog(PmpCodeUtils.class);

	private static String LIST = "code.do?action=list";
	private static String GET = "code.do?action=get";

	public static void init() {

	}

	@SuppressWarnings("unchecked")
	public static List<Code> list(final String sortType) {
		final Map<String, Object> params = new HashMap<String, Object>();
		params.put("sortType", sortType);
		final String result = HttpUtils.postForString(SecurityConfig.getAuthUrl(LIST), params);
		if (StringUtils.isBlank(result)) {
			log.error("can not get anything from AuthServer for getCodeList");
			return Collections.EMPTY_LIST;
		}
		final RespInfo<List<Code>> respInfo = JSON.parseObject(result, new TypeReference<RespInfo<List<Code>>>() {
		});

		if (!respInfo.isSuccess()) {
			return Collections.EMPTY_LIST;
		}

		if (respInfo.getResult() == null) {
			return Collections.EMPTY_LIST;
		}

		return respInfo.getResult();
	}

	public static Code get(final String sortType, final String value) {
		final Map<String, Object> params = new HashMap<String, Object>();
		params.put("sortType", sortType);
		params.put("value", value);
		final String result = HttpUtils.postForString(SecurityConfig.getAuthUrl(GET), params);
		if (StringUtils.isBlank(result)) {
			log.error("can not get anything from AuthServer for getCode");
			return null;
		}
		final RespInfo<Code> respInfo = JSON.parseObject(result, new TypeReference<RespInfo<Code>>() {
		});

		if (!respInfo.isSuccess()) {
			return null;
		}

		return respInfo.getResult();
	}
}
